# -*- coding: utf-8 -*-
#-----------------------------------------
# @Time       : 2018/6/18 9:27
# @Author     : dqz 
# @Email      : 1406990390@qq.com
# @File       : __init__.py
# @Software   : PyCharm
#-----------------------------------------


import datetime
import functools
import json
import os

import flask
from flask import jsonify
from flask_cors import CORS


# Json 无法解析 datatime 类型的数据，构建 DateEncoder 类解决 datatime 解析问题
class DateEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime.datetime):
            return obj.strftime("%Y-%m-%d %H:%M:%S")
        else:
            return json.JSONEncoder.default(self, obj)


json.dumps = functools.partial(json.dumps, cls=DateEncoder)


def create_app(config=None):
    app = flask.Flask(__name__)
    # 支持全局跨域
    CORS(app)
    # load default configuration
    app.config.from_object('settings')
    import diff, sync, info
    # load environment configuration
    if 'FLASK_CONF' in os.environ:
        app.config.from_envvar('FLASK_CONF')
    # load apps sepcified configuration
    if config is not None:
        if isinstance(config, dict):
            app.config.update(config)
        elif config.endswith('.py'):
            app.config.from_pyfile(config)

    diff.init_app(app)
    sync.init_app(app)
    info.init_app(app)

    @app.route("/health")
    def health():
        return jsonify("I am OK!")

    return app


if __name__ == '__main__':
    app = create_app()
    app.run(host='localhost', port=5000)
